package controller.company;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.company.AllCompanyFeedAdapter;
import define.API;
import define.Key;
import model.company.CompanyFeedItem;
import model.company.ShotOfCompanyFeedItem;
import ui.fragment.company.AllCompanyFeedFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class AllCompanyFeedAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String TITLE = "";
    private String SPLASH = "";
    private String UPLOAD_TIME = "";
    private String OBJECT = "";
    private String PREVIEW_MEDIUM = "";
    private int content_type = 0 ;
    private long shot_id = 0;
    private long global_shot_id = 0;

    private long company_id = 0;
    private String COMPANY_NAME = "";
    private long group_id = 0;
    private String GROUP_NAME = "";
    private int number_of_shots = 0;
    private String USER_AVATAR = "" ;
    private String USER_NAME = "";
    private String ELAPSED_TIME= "";
    private String ADDED_DATE = "";

    private String ERROR = "";
    private String STATUS = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <CompanyFeedItem> mAlAllCompanyFeed = new ArrayList<>();
    public static ArrayList <Long> mAlGroupId = new ArrayList<>();
    public static ArrayList <Long> mAlShotId = new ArrayList<>();

    public AllCompanyFeedAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (!mAlAllCompanyFeed.isEmpty())
            mAlAllCompanyFeed.clear();
        if (!mAlShotId.isEmpty())
            mAlShotId.clear();
        if (!mAlGroupId.isEmpty())
            mAlGroupId.clear();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            AllCompanyFeedFragment.allCompanyFeedAdapter = new AllCompanyFeedAdapter(
                    mContext,R.layout.simple_list_item_all_company_feed, mAlAllCompanyFeed);
            AllCompanyFeedFragment.mLvInAllCompanyFeedFragment.setAdapter(AllCompanyFeedFragment.allCompanyFeedAdapter);
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_ALL_COMPANY_FEED_AND_COMPANY_FEED);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_MODE, params[2]));
        mListValues.add(new BasicNameValuePair(Key.PAGE_INDEX, params[3]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", AllCompanyFeedAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get mJaCompanyFeeds in mJoXml
                JSONArray mJaCompanyFeeds = mJoXml.getJSONArray(Key.COMPANY_FEEDS);
                if (!"[]".equals(mJaCompanyFeeds.toString())) {
                    for (int i = 0; i <mJaCompanyFeeds.length(); i++) {
                        //get mJoCompanyFeeds in mJaCompanyFeeds
                        JSONObject mJoCompanyFeeds = mJaCompanyFeeds.getJSONObject(i);
                        //get string in mJoCompanyFeeds
                        company_id = mJoCompanyFeeds.getLong(Key.COMPANY_ID);
                        COMPANY_NAME = mJoCompanyFeeds.getString(Key.COMPANY_NAME);
                        group_id = mJoCompanyFeeds.getLong(Key.GROUP_ID);
                        GROUP_NAME = mJoCompanyFeeds.getString(Key.GROUP_NAME);
                        number_of_shots = mJoCompanyFeeds.getInt(Key.NUMBER_OF_SHOTS);
                        USER_AVATAR = mJoCompanyFeeds.getString(Key.USER_AVATAR);
                        USER_NAME = mJoCompanyFeeds.getString(Key.USER_NAME);
                        ELAPSED_TIME = mJoCompanyFeeds.getString(Key.ELAPSED_TIME);
                        ADDED_DATE = mJoCompanyFeeds.getString(Key.ADDED_DATE);
                        ArrayList <ShotOfCompanyFeedItem> mAlShotOfCompanyFeedItem = new ArrayList<>();
                        //get mJaShots in mJoCompanyFeeds
                        JSONArray mJaShots = mJoCompanyFeeds.getJSONArray(Key.SHOTS);
                        if (!"[]".equals(mJaShots.toString())) {
                            //get mJoShots in mJaShots
                            for (int j = 0; j < mJaShots.length(); j++) {
                                JSONObject mJoShots = mJaShots.getJSONObject(j);
                                //get string in mJoShots
                                TITLE = mJoShots.getString(Key.TITLE);
                                SPLASH = mJoShots.getString(Key.SPLASH);
                                UPLOAD_TIME = mJoShots.getString(Key.UPLOAD_TIME);
                                OBJECT = mJoShots.getString(Key.OBJECT);
                                PREVIEW_MEDIUM = mJoShots.getString(Key.PREVIEW_MEDIUM);
                                content_type = mJoShots.getInt(Key.CONTENT_TYPE);
                                shot_id = mJoShots.getLong(Key.SHOT_ID);
                                global_shot_id = mJoShots.getLong(Key.GLOBAL_SHOT_ID);

                                ShotOfCompanyFeedItem shotOfCompanyFeedItem = new ShotOfCompanyFeedItem(
                                        TITLE, SPLASH, UPLOAD_TIME, OBJECT,
                                        PREVIEW_MEDIUM, content_type, shot_id,
                                        global_shot_id
                                );
                                if (!mAlShotId.contains(shot_id)) {
                                    mAlShotOfCompanyFeedItem.add(shotOfCompanyFeedItem);
                                    mAlShotId.add(shot_id);
                                }
                            }
                        }

                        CompanyFeedItem companyFeedItem = new CompanyFeedItem(
                                company_id, COMPANY_NAME, group_id,
                                GROUP_NAME, number_of_shots, USER_AVATAR,
                                USER_NAME, ELAPSED_TIME, ADDED_DATE,
                                mAlShotOfCompanyFeedItem
                        );
                        if (!mAlGroupId.contains(group_id)) {
                            mAlAllCompanyFeed.add(companyFeedItem);
                            mAlGroupId.add(group_id);
                        }
                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}